"""
文件的读写操作
"""
import json
import os

def create_package(path):
    if os.path.exists(path):
        raise Exception('%s 已经存在不可创建' % path)
    os.makedirs(path)
    init_path = os.path.join(path, '__init__.py')
    f = open(init_path, 'w')
    f.write('# coding:utf-8\n')
    f.close()

#封装了open的功能，使它可以默认换行
class Open(object):
    def __init__(self, path, mode='w', is_return=True):
        self.path = path
        self.mode = mode
        self.is_return = is_return

    def write(self, message):
        f = open(self.path, mode=self.mode,encoding='utf-8') #'w'覆盖内容，'a'增加内容
        if self.is_return:
            message = '%s\n' % message
        f.write(message)
        f.close()

    def read(self, is_strip=True):
        result = []
        with open(self.path, mode=self.mode,encoding='utf-8') as f:
            data = f.readlines() #返回列表
        for line in data:
            if is_strip == True:
                temp = line.strip() #去掉换行符
                if temp != "": #去掉换行符后不为空
                    result.append(temp)
            else:
                if line != '':
                    result.append(line)
        return result

if __name__ == '__main__':
    current_path = os.getcwd() #获得当前路径
    path = os.path.join(current_path, 'test1')
    # create_package(path) #在当前路径/test1下，创建符合pytho标准的包
    open_path = os.path.join(path, 'a.txt')
    o = Open(open_path, mode='a') #写文件
    o.write('# 你好 winner')

    read_o = Open(open_path, mode='r')
    print(read_o.read())



"""
json对象序列化，python的pickle模块也可以序列化反序列化
"""
#set、class、def不能序列号
json.dumps([1,2,3]) #对象序列化，返回字符串
json.loads('[1,2,3]') #返序列化，返回原始类型